import Picker from '@see_you/react-native-picker';
import {useAppTheme} from 'tsun-smart-ui';
import {useEffect, useLayoutEffect, useMemo, useRef, useState} from 'react';
import dayjs from 'dayjs';
import {useTranslation} from 'react-i18next';
import {ApiResponse} from '@/services/http';
import {Unit} from '@/enums/statistics';
import {useWindowDimensions} from 'react-native';
import {BaseChart} from '@see_you/react-native-charts-wrapper';
import toast from '@/utils/toast';
import {useIsFocused} from '@react-navigation/native';
export const processColor = (color: string): number[] => {
  let hex = color.replace('#', '');
  if (hex.length === 3) {
    hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
  }
  let r = 0,
    g = 0,
    b = 0;
  let a: number = 1;
  if (hex.length === 8) {
    r = parseInt(hex.substring(0, 2), 16);
    g = parseInt(hex.substring(2, 4), 16);
    b = parseInt(hex.substring(4, 6), 16);
    a = parseInt(hex.substring(6, 8), 16) / 255;
  } else if (hex.length === 6) {
    r = parseInt(hex.substring(0, 2), 16);
    g = parseInt(hex.substring(2, 4), 16);
    b = parseInt(hex.substring(4, 6), 16);
  }
  return [r, g, b, a];
};

// 定义日期选择器的类型
export type DatePickerMode = 'year' | 'month' | 'day' | 'total';

// 生成年份数组
const generateYears = (minYear: number, maxYear: number): string[] => {
  const years: string[] = [];
  for (let year = minYear; year <= maxYear; year++) {
    years.push(year.toString());
  }
  return years;
};

// 生成年月日级联选择数据
export const generateYearMonthDayPickerData = (
  minDate: dayjs.Dayjs,
  maxDate: dayjs.Dayjs,
): any[] => {
  const minYear = minDate.year();
  const maxYear = maxDate.year();

  const cascadingData: any[] = [];

  const currentDate = dayjs();

  for (let year = minYear; year <= maxYear; year++) {
    const yearObj: any = {};
    const monthsArray: any[] = [];

    // 确定当前年份的月份范围
    let maxMonth = 12;
    if (year === currentDate.year()) {
      maxMonth = currentDate.month() + 1; // dayjs月份从0开始，所以+1
    }

    for (let month = 1; month <= maxMonth; month++) {
      const monthString = month.toString().padStart(2, '0');
      const monthObj: any = {};
      const daysInMonth = dayjs(`${year}-${month}`).daysInMonth();
      const daysArray: string[] = [];

      // 确定当前月份的日期范围
      let maxDay = daysInMonth;
      if (year === currentDate.year() && month === currentDate.month() + 1) {
        maxDay = currentDate.date(); // 当前日期
      }

      for (let day = 1; day <= maxDay; day++) {
        daysArray.push(day.toString());
      }
      monthObj[monthString] = daysArray;
      monthsArray.push(monthObj);
    }

    yearObj[year.toString()] = monthsArray;
    cascadingData.push(yearObj);
  }

  return cascadingData;
};

// 生成年月级联选择数据（级联结构）
export const generateYearMonthPickerData = (
  minDate: dayjs.Dayjs,
  maxDate: dayjs.Dayjs,
): any[] => {
  const minYear = minDate.year();
  const maxYear = maxDate.year();
  const currentDate = dayjs();
  const cascadingData: any[] = [];
  for (let year = minYear; year <= maxYear; year++) {
    const yearObj: any = {};
    const monthsArray: any[] = [];

    // 确定当前年份的月份范围
    let maxMonth = 12;
    if (year === currentDate.year()) {
      maxMonth = currentDate.month() + 1; // dayjs月份从0开始，所以+1
    }

    for (let month = 1; month <= maxMonth; month++) {
      const monthString = month.toString().padStart(2, '0');
      monthsArray.push(monthString);
    }

    yearObj[year.toString()] = monthsArray;
    cascadingData.push(yearObj);
  }

  return cascadingData;
};
// 更新后的 useDatePicker hook
const useDatePicker = <T extends ApiResponse>(
  unit: DatePickerMode,
  api: (params: any) => Promise<T>,
  params?: any,
) => {
  const {t} = useTranslation();
  const [loading, setLoading] = useState(false);
  const chartRef = useRef<BaseChart<any>>(null);
  const theme = useAppTheme();
  const [result, setResult] = useState<T['data']>([]);
  const isFocused = useIsFocused();
  const minDate = dayjs('2019-1-1');
  const maxDate = dayjs();
  const {width} = useWindowDimensions();
  const [currentUnit, setCurrentUnit] = useState(unit);
  const [selectedValue, setSelectedValue] = useState(dayjs());
  const pickerData = useMemo(() => {
    switch (unit) {
      case 'day':
        return generateYearMonthDayPickerData(minDate, maxDate);
      case 'month':
        return generateYearMonthPickerData(minDate, maxDate);
      case 'year':
        return generateYears(minDate.year(), maxDate.year());
      default:
        return [];
    }
  }, [unit]);
  useLayoutEffect(() => {
    requestAnimationFrame(() => {
      toast[loading && isFocused ? 'showLoading' : 'hideLoading']();
    });
    return toast.hideLoading;
  }, [loading, isFocused]);
  useEffect(() => {
    setLoading(true);
    api({
      grain: Unit[unit],
      year: unit ? selectedValue.get('year') : dayjs().get('year'),
      month:
        unit === 'month' || unit === 'day'
          ? selectedValue.get('month') + 1
          : undefined,
      day: unit === 'day' ? selectedValue.get('D') : undefined,
      ...params,
    })
      .then(({data}) => {
        setResult(data);
        requestAnimationFrame(() => {
          chartRef.current?.fitScreen();
          chartRef.current?.highlights([]);
        });
        setCurrentUnit(unit);
      })
      .finally(() => {
        setLoading(false);
      });
  }, [unit, selectedValue, params]);
  useEffect(() => {
    Picker.init({
      pickerCancelBtnColor: processColor(theme.colors?.brand?.primary!),
      pickerConfirmBtnColor: processColor(theme.colors?.brand?.primary!),
      pickerTitleText: '',
      pickerBg: processColor(theme.colors?.neutral?.white!),
      pickerToolBarBg: processColor(theme.colors?.neutral?.white!),
      pickerData: pickerData,
      pickerRowHeight: 48,
      pickerFontSize: 15,
      selectedValue: selectedValue.format('YYYY-MM-D').split('-'),
      onPickerConfirm: (pickedValue: string[]) => {
        pickedValue.length > 0 &&
          setSelectedValue(dayjs(pickedValue.join('-')));
      },
      pickerCancelBtnText: t('user.logOutCancel', {defaultValue: '取消'}),
      pickerConfirmBtnText: t('common.confirmButtonText', {
        defaultValue: '确认',
      }),
      pickerFontColor: processColor(theme.colors?.neutral?.title!),
    });
  }, [pickerData, theme, width]);

  return {
    Picker,
    selectedValue,
    setSelectedValue,
    result,
    loading,
    chartRef,
    currentUnit
  } as const;
};

export default useDatePicker;
